export default {
	namespaced: true,
	state() {
		return {
			// 初始的状态数据
			test: '哈哈',
			carts: uni.getStorageSync('carts') || []
		}
	},
	getters: {
		cartCount(state) {
			return state.carts.length;
		},
		allChecked(state) {
			return state.carts.every((item) => item.goods_state);
		}
	},
	mutations: {
		toggleAll(state, allChecked) {
			// 遍历数据将全部商品的状态修改
			state.carts.forEach((item) => item.goods_state = !allChecked);
		},
		// 购物车中的数量 减
		decreaseCount(state, index) {
			if (state.carts[index].goods_number <= 1) return
			state.carts[index].goods_number--
			// 存入本地
			this.commit('m_cart/saveToStorage')
		},
		// 加
		increaseCount(state, index) {
			state.carts[index].goods_number++
			// 存入本地
			this.commit('m_cart/saveToStorage')
		},
		toggleState(state, index) {
			state.carts[index].goods_state = !state.carts[index].goods_state;
			// console.log(index);
			// 存入本地
			this.commit('m_cart/saveToStorage')
		},
		addToCart(state, goods) {
			// console.log(state);
			// console.log(goods);
			// 查找是否已经存在相同商品
			const result = state.carts.find(item => item.goods_id === goods.goods_id)
			if (!result) {
				// console.log('没同有相同商品');
				state.carts.push(goods);
			} else {
				// console.log('有相同商品');
				result.goods_number += 1
			}
			// 存入本地
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			// 将购物车数据存入本地
			uni.setStorageSync('carts', state.carts);
		}
	}
}
